package com.suyl.httpsdemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author suyanlong
 * @version 1.0
 * @createDate 2020/3/18 21:07
 */
@Configuration
@EnableAsync
public class ExecutorConfig {
    @Bean
    public Executor asyncServiceExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(10); // 核心线程数
        threadPoolTaskExecutor.setMaxPoolSize(20); // 最大线程数
        threadPoolTaskExecutor.setKeepAliveSeconds(60); //
        threadPoolTaskExecutor.setQueueCapacity(200); // 配置队列大小
        threadPoolTaskExecutor.setThreadNamePrefix("async-service-"); // 线程名称的前缀
        // 设置拒绝策略：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        threadPoolTaskExecutor.setAwaitTerminationSeconds(100);
        // 执行初始化
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;

    }
}
